"use strict";
import { getDocData } from "./tool/getDocData";
import { util, BaseErr } from "utils";
import { createContent, toQWPush, toDingDingPush } from "./tool/postQW";
import { getGroupPushContent } from "./tool/getGroupPushContent";

exports.main = async (event, context) => {
    // console.log("event ---", JSON.stringify(event, null, 2));
    let { Type } = event || {};
    const currentIsTiming = Type === "Timer";

    if (!currentIsTiming) {
        // 不是定时任务, 校验签名
        let signErrResult = util.checkSign(event);
        if (!util.nilValue(signErrResult)) {
            return signErrResult;
        }
    }

    // 获取数据
    let [doc_err, doc_data] = await getDocData();
    if (doc_err) {
        if (currentIsTiming) {
            await toQWPush(createContent(doc_err));
        }
        return util.resErr(doc_err);
    }

    let docArr = Array.isArray(doc_data) ? doc_data : [];
    // 四组
    let sizuIndex = docArr.findIndex((e) => {
        return e.des.indexOf("第四组") >= 0;
    });
    if (sizuIndex < 0) {
        let msg = "没有第四组的数据啊...";
        if (currentIsTiming) {
            await toQWPush(createContent(msg));
        }
        return util.resErr(new BaseErr(-3101, msg));
    }

    // 只要 第四组数据
    let sizuList: any[] = docArr[sizuIndex].list;
    if (currentIsTiming) {
        let sep = "  \r\n  ";
        // 处理 推送的内容
        let [groupContent, atMobiles] = getGroupPushContent(sizuList, sep);
        if (atMobiles && atMobiles.length > 0) {
            let notifyUsers = atMobiles.map((e) => `@${e}`).join(" ");
            groupContent = [groupContent, notifyUsers].join(sep);
        }
        let pushContent = createContent(groupContent);
        await toDingDingPush(pushContent, atMobiles);
    }
    // 返回
    return util.resData(sizuList);
};
